<template>
	<view class="pushDynamic">
		<tui-navigation-bar :titleSize="18" :titleLineHeight="18" :titlefontWeight="800" :isOpacity="false"
			@init="initNavigation" title="发布动态" backgroundColor="#fff" color="#000">
			<view class="tui-header-icon" :style="{ marginTop: top + 'px' }">
				<tui-icon name="arrowleft" color="#333" @click="back"></tui-icon>
			</view>
		</tui-navigation-bar>
		<view class="pushDynamic_content" :style="{ paddingTop: marginTp + 'px' }">
			<tui-textarea v-model="releaseContent" :size="24" :borderBottom="false" :borderTop="false" height="40rpx" min-height="40rpx" placeholder="请输入动态~"></tui-textarea>
			<!-- <tui-upload :value="value" :serverUrl="serverUrl" @complete="result" @remove="remove"></tui-upload> -->
			<tui-upload delConfirm isDel  addSize="32" width="148" :size="5" height="148" radius="24"  delColor="#FFFFFF" :value="imageList" ref="uploadRef" @remove="remove" @complete="complete" @reupload="reUpload"></tui-upload>
			<view class="select_address">
			<view class="arrowleft" @tap="selectAdress">
				<view class="address_icon">
					<image class="icon" src="../../../../static/user/find/icon_dingwei11@2x.png"></image>
				</view>
				<view class="address_text"><text>{{addressInfo.name}}</text></view>
			</view>
				<tui-icon name="arrowright" size="40"></tui-icon>
			</view>
		</view>
		<view class="footer">
				<tui-form-button radius="40rpx" :size="32" color="#fff" width="200rpx" height="84rpx" background="#ccc">
					保存草稿
				</tui-form-button>
				<tui-form-button :pushLoading="pushLoading" @click="confirmPush" radius="40rpx" :size="32" color="#fff" width="460rpx" height="84rpx" background="#2FD7D3"> 
					确认发布
				</tui-form-button>
		</view>
	</view>
</template>

<script> 
	import Cache from '@/utils/cache'
	import config from '@/common/config.js'
	import { pushDynamic } from "@/http/api/dynamic/dynamic.js" 
	import { delUploadFile } from "@/http/api/uploadFiles/uploadFiles.js" 
	export default {
		data() {
			return {
				top: 0, //标题图标距离顶部距离
				marginTp: 0,
				isAgreement: false,
				pushLoading:false,
				releaseContent:'',//发布内容
				visible: false, //邀约填写项
				atciveIndex: 0, //切换商家图片和教练列表
				imageData: [],
				addressInfo:{
					latitude: '', // 纬度
					longitude: '', // 经度
					name: '', // 名称
					province: '', // 省份
					city: '', // 市区
					district: '', // 区域
					businessAreaName: '', // 商圈
				},
				//上传接口地址
				serverUrl: "/resource/app/oss/upload",
			    isUploading: false, // 是否正在上传	
				imageList:[], //初始化图片
				arris:0
			}
		}, 
		onUnload() {
			uni.$off('adressInfo')
		},
		onLoad() {
			this.addressInfo.longitude=Cache.get('longitude')
			this.addressInfo.latitude=Cache.get('latitude')
			this.addressInfo.name=Cache.get('adressNmae') 
			uni.$on('adressInfo',(e)=>{
				this.addressInfo.latitude=e.latitude
				this.addressInfo.longitude=e.longitude
				this.addressInfo.name=e.name
				this.addressInfo=e
			}) 
		}, 
		methods: {
			//以下为调用upload 方法上传示例
			  	//注：上传成功或失败处理，请按照下方示例返回(resolve, reject)信息，请勿修改格式
			  	uploadImg(file) {
					let token = Cache.get('access_token'); 
					uni.showLoading({
						title: '上传中...'
					})
			  		//上传的文件信息
			  		// 文件上传的函数，返回一个promise
			  		//上传成功后返回上传后的图片地址，上传失败则返回false即可
			  		return new Promise((resolve, reject) => {
			  			//调用api上传，所有需要参数自行补充【上传自行实现，便于扩展】
			  			uni.uploadFile({
			  				//请换成真实的上传接口地址，示例接口已关闭
			  				url:config.http.baseURL + this.serverUrl,
			  				name: 'file',
			  				header: {
								Authorization: 'Bearer ' + token
							},
			  				// formData:{},
			  				filePath: file.path,
			  				success: (res) => {
			  					//上传成功后，将图片地址返回  
			  					if (res.statusCode===200) {
			  						//返回上传成功后的图片地址，根据实际接口返回处理数据 
			  						const data = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
			  						let url = data.data.url
									let imgObject={
										url,
										img:data.data.fileName,
										ossId:data.data.ossId
									}
									this.imageList.push(imgObject) 
			  						//上传成功后务必返回图片地址信息
			  						resolve(url)
			  					} else {
			  						//上传失败
			  						reject(false)
			  					}
								uni.hideLoading();
			  				},
			  				fail: (err) => {
								uni.hideLoading();
			  					//上传失败
			  					console.log(err)
			  					reject(false)
			  				}
			  			})
			  		})
			  	},
				//确认发布
			   confirmPush(){ 
					if(!this.releaseContent){
						 this.$utils.toast('请输入发布内容！')
						return;
					}
					if(this.imageList.length===0){
						 this.$utils.toast('请选择图片！')
						return;
					}  
					this.pushLoading=true
					const imgs=this.imageList.map(item=>item.img)
					pushDynamic({
						releaseContent:this.releaseContent,
						coordinates:{
							lat:this.addressInfo.latitude,
							lng:this.addressInfo.longitude
						},
						poi:this.addressInfo.poi,
						fromType:1,
						userId:Cache.get('userId'),
						releaseImgs:imgs
					}).then( res =>{
						if (res.code == 200) {
							 this.$utils.toast('发布成功')
							 uni.$emit('myDynamicRefresh',true)
							 uni.navigateBack();
						} else {
							this.$utils.toast(res.msg);
						}
					})
					.finally(()=>{ 
						this.pushLoading = false;
						this.isUploading = false; // 重置上传状态
					})
				},
			  	//重新上传
			  	reUpload(e) {
			  		//当前上传按钮索引值
			  		console.log(e.index)
			  		//调用upload 方法上传，并传入函数，且此时需要传入index值
			  		this.$refs.uploadRef && this.$refs.uploadRef.upload(this.uploadImg, e.index)
			  	},
				//图片本地上传完成
			  	complete(e) { 
					if (e.status === 2 && !this.isUploading) { // 上传中且未在上传
						this.isUploading = true; // 标记为正在上传
						this.$refs.uploadRef && this.$refs.uploadRef.upload(this.uploadImg)
						this.arris=e.imgArr.length 
					  } 
					  if(this.arris===this.imageList.length){
						  this.isUploading = false; 
					  }
			  	},
				//删除图片
				remove(e){ 
					this.$refs.uploadRef.delImgConfim(e.index)
					this.imageList.splice(e.index, 1);
				},
			initNavigation(e) {
				this.top = e.top;
				this.marginTp = e.height
			},
			back() {
				uni.navigateBack();
			},
			closeDrawer() {
				this.visible = false
			},
			examine(arr, index) {
				uni.previewImage({
					urls: arr,
					current: index
				});
			},
			clickSwtichTab(data) {
				this.atciveIndex = data.index
			},
			selectAdress(){
				let info =this.addressInfo
				uni.navigateTo({
					url:'/pages/index/modules/addressSelect/addressSelect?info='+JSON.stringify(info)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import './pushDynamic.scss';
::v-deep .tui-img-del {
  position: relative; /* 必须为父元素设置相对定位 */
  top: 12rpx!important;
  right: 12rpx!important;
  width: 17rpx!important;
  height: 17rpx!important;
  background-color: white;  /* 如果需要背景色 */
  border-radius: 50%;  /* 使其变为圆形 */
}

::v-deep .tui-img-del::after {
  content: "X";  /* 插入 X 字符 */
  font-size: 12rpx;  /* X 字符的大小 */
  color: #000;  /* X 字符的颜色 */
  position: absolute;
  top: 50%;  /* 垂直居中 */
  left: 50%;  /* 水平居中 */
  transform: translate(-50%, -50%); /* 完全居中 */
}
</style>